package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.util.FileUploadUtils;
import com.ruoyi.system.domain.Attachements;
import com.ruoyi.system.domain.Cheyouhui;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.IAdverinfoService;
import com.ruoyi.system.service.IAttachementsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Adverinfo;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 广告 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-07-16
 */
@Controller
@RequestMapping("/system/adverinfo")
public class AdverinfoController extends BaseController
{

	private static final Logger log = LoggerFactory.getLogger(AdverinfoController.class);
	private String prefix = "system/adverinfo";
	
	@Autowired
	private IAdverinfoService adverinfoService;
	@Autowired
	private IAttachementsService attachementsService;

	@RequiresPermissions("system:adverinfo:view")
	@GetMapping()
	public String adverinfo()
	{
	    return prefix + "/adverinfo";
	}
	
	/**
	 * 查询广告列表
	 */
	@RequiresPermissions("system:adverinfo:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Adverinfo adverinfo)
	{
		startPage();
        List<Adverinfo> list = adverinfoService.selectAdverinfoList(adverinfo);
        for(Adverinfo adverinfo1:list){
        	Attachements attachements = attachementsService.findByOfId(adverinfo1.getAdvertinfoId());
        	if(attachements != null){
        		adverinfo1.setAttribute(attachements.getPath());
			}
		}
		return getDataTable(list);
	}
	
	
	/**
	 * 导出广告列表
	 */
	@RequiresPermissions("system:adverinfo:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Adverinfo adverinfo)
    {
    	List<Adverinfo> list = adverinfoService.selectAdverinfoList(adverinfo);
        ExcelUtil<Adverinfo> util = new ExcelUtil<Adverinfo>(Adverinfo.class);
        return util.exportExcel(list, "adverinfo");
    }
	
	/**
	 * 新增广告
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	/**
	 * 新增保存广告
	@RequiresPermissions("system:adverinfo:add")
	@Log(title = "广告", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(HttpServletRequest request, Adverinfo adverinfo, MultipartFile[] files)
	{
		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {

				Map<String, Object> fileInfo = saveFile(request,file);
				if (fileInfo != null) {
					Attachements attachement = new Attachements();
					attachement.setBeizhu(adverinfo.getUid());
					SysUser user = getSysUser();
					attachement.setModifyId(String.valueOf(user.getUserId()));

					attachement.setStatus(0);
					attachement.setCreateId(String.valueOf(user.getUserId()));

					attachement.setMc(fileInfo.get("name").toString());
					attachement.setPath(fileInfo.get("path").toString());
					attachement.setSuffix(fileInfo.get("suffix").toString());
					attachement.setLen(fileInfo.get("size").toString());

					attachementsService.insertAttachements(attachement);

				}
			}
		}
		return toAjax(adverinfoService.insertAdverinfo(adverinfo));
	}*/

	/**
	 * 新增保存广告
	 */
	@RequiresPermissions("system:adverinfo:add")
	@Log(title = "广告", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(@RequestParam("files") MultipartFile files,Adverinfo adverinfo)
	{
		try
		{
		if (!files.isEmpty()) {
			//上传路径
			String avatar = FileUploadUtils.upload(Global.getGuanggaoPath(), files);
			adverinfo.setImgPath(avatar);

			return toAjax(adverinfoService.insertAdverinfo(adverinfo));
		}
			return error();
		}
		catch (Exception e)
		{
			log.error("保存广告图片失败！", e);
			return error(e.getMessage());
		}


	}

	/**
	 * 修改广告
	 */
	@GetMapping("/edit/{advertinfoId}")
	public String edit(@PathVariable("advertinfoId") Integer advertinfoId, ModelMap mmap)
	{
		Adverinfo adverinfo = adverinfoService.selectAdverinfoById(advertinfoId);
		mmap.put("adverinfo", adverinfo);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存广告
	 */
	@RequiresPermissions("system:adverinfo:edit")
	@Log(title = "广告", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(HttpServletRequest request,Adverinfo adverinfo, @RequestParam("files")MultipartFile files)
	{
		try
		{
			if (!files.isEmpty()) {
				//上传路径
				String avatar = FileUploadUtils.upload(Global.getGuanggaoPath(), files);
				adverinfo.setImgPath(avatar);

				return toAjax(adverinfoService.insertAdverinfo(adverinfo));
			}
			return error();
		}
		catch (Exception e)
		{
			log.error("保存广告图片失败！", e);
			return error(e.getMessage());
		}

	}
	
	/**
	 * 删除广告
	 */
	@RequiresPermissions("system:adverinfo:remove")
	@Log(title = "广告", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(adverinfoService.deleteAdverinfoByIds(ids));
	}



	/**
	 * 广告照片添加界面
	 */
	@GetMapping("/zhaopian/{advertinfoId}")
	public String zhaopian(@PathVariable("advertinfoId") Integer advertinfoId, ModelMap mmap)
	{
		Adverinfo adverinfo = adverinfoService.selectAdverinfoById(advertinfoId);

		Attachements attachements = attachementsService.findByOfId(adverinfo.getAdvertinfoId());

		mmap.put("attachement",attachements);
		mmap.put("adverinfo", adverinfo);
		mmap.put("advertinfoId",advertinfoId);
		return prefix + "/zhaopian";
	}
	/**
	 * 广告照片查看界面
	 */
	@GetMapping("/chakan/{advertinfoId}")
	public String chakan(@PathVariable("advertinfoId") Integer advertinfoId, ModelMap mmap)
	{
		Adverinfo adverinfo = adverinfoService.selectAdverinfoById(advertinfoId);


		mmap.put("adverinfo", adverinfo);

		return prefix + "/chakan";
	}

	/**
	 * 图片预览
	 * @param advertinfoId
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@GetMapping("/downloadFile/{advertinfoId}")
	public void downloadFile(@PathVariable("advertinfoId") Integer advertinfoId, HttpServletResponse response,
							 HttpServletRequest request) throws Exception
	{
		Adverinfo adverinfo = adverinfoService.selectAdverinfoById(advertinfoId);
		String filePath = adverinfo.getImgPath();

		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");

		FileUtils.writeBytes(filePath, response.getOutputStream());
	}

}


